import { createRouter, createWebHashHistory } from 'vue-router'
import { tokenUtils } from '@/utils/token'

const routes = [
  {
    path: '/',
    redirect: '/chat'
  },
  {
    path: '/chat',
    name: 'Chat',
    component: () => import('@/views/Chat.vue'),
    meta: {
      requiresAuth: true,
      title: 'AI图片分析'
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: {
      requiresAuth: false,
      title: '用户登录'
    }
  },
  {
    path: '/example',
    name: 'Example',
    component: () => import('@/views/Example.vue'),
    meta: {
      requiresAuth: true,
      title: 'API示例'
    }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/'
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const hasToken = tokenUtils.exists()

  document.title = to.meta?.title || 'AI图片分析'

  if (to.meta.requiresAuth) {
    if (hasToken) {
      next()
    } else {
      next({
        path: '/login',
        query: {
          redirect: to.fullPath
        }
      })
    }
  } else {
    if (to.path === '/login' && hasToken) {
      next('/')
    } else {
      next()
    }
  }
})

export default router